<?php
namespace plugin\ky_shouyin\app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class CheckAuth implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        $user = session('user');
        
        // 如果是前台收银页面，检查会话状态
        if ($request->path() === '/app/ky_shouyin/front/cashier/index') {
            if (!$user) {
                if ($request->isAjax()) {
                    return json(['code' => 401, 'msg' => '请重新登录']);
                }
                return redirect('/app/ky_shouyin/admin/account/login');
            }
            // 刷新会话
            session()->set('user', $user);
        }
        
        // 登录页面不需要验证
        if ($request->path() === '/app/ky_shouyin/admin/account/login') {
            return $handler($request);
        }
        
        // 检查是否登录
        if (!$user) {
            if ($request->isAjax()) {
                return json(['code' => 401, 'msg' => '请先登录']);
            }
            return redirect('/app/ky_shouyin/admin/account/login');
        }
        
        // 检查访问权限
        $path = $request->path();
        if (strpos($path, '/admin/') !== false && 
            (int)$user['role'] === 4 && 
            !in_array($path, [
                '/app/ky_shouyin/admin/account/login',
                '/app/ky_shouyin/admin/account/logout',
                '/app/ky_shouyin/admin/account/captcha/login'
            ])
        ) {
            if ($request->isAjax()) {
                return json(['code' => 403, 'msg' => '无权访问']);
            }
            return redirect('/app/ky_shouyin/front/cashier/index');
        }
        
        return $handler($request);
    }
} 